#include "ota_memchunk.h"
#include <stdlib.h>
#include <string.h>

MemChunk *ota_memchunk_init()
{
    MemChunk *chunk = (MemChunk *)malloc(sizeof(MemChunk));
    if (!chunk)
    {
        return NULL;
    }
    chunk->data = malloc(1);
    if (!chunk->data)
    {
        free(chunk);
        return NULL;
    }
    chunk->data[0] = '\0';
    chunk->size = 0;
    return chunk;
}

int ota_memchunk_append(MemChunk *chunk, void *data, size_t len)
{
    void *temp = realloc(chunk->data, chunk->size + len + 1);
    if (!temp)
    {
        return -1;
    }

    chunk->data = temp;
    memcpy(chunk->data + chunk->size, data, len);
    chunk->size += len;
    chunk->data[chunk->size] = '\0';
    return 0;
}

void ota_memchunk_destroy(MemChunk *chunk)
{
    if (chunk)
    {
        free(chunk->data);
        free(chunk);
    }
}
